package ctrl;

import entities.Booking;
import entities.GuestUser;
import hotel.jpa.BookingJpaCtrl;
import hotel.jpa.Database;
import hotel.jpa.IBookingJpaCtrl;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import model.MyPageBackingBean;

/**
 *
 * @author Anton Karlsson
 */
@ManagedBean(name = "myPageControllerBean")
@SessionScoped
public class MyPageControllerBean {

    List<Booking> mybookings = new ArrayList<Booking>();
    Booking myBooking = null;

    public List<Booking> getMybookings() {

        //Get the user who is logged in 
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession session = req.getSession();
        GuestUser aUser = (GuestUser) session.getAttribute("loginUser");

        //Get the users bookings
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("hotel_pu");
        IBookingJpaCtrl bookingCtrl = new BookingJpaCtrl(null, emf);

        mybookings = bookingCtrl.findMyBookings(aUser);

        return mybookings;
    }

    public void setMybookings(List<Booking> b) {
        this.mybookings = b;
    }
    
    public Booking getMyBooking(Long id) {
        mybookings = getMybookings();
        
        for(int i = 0; i < mybookings.size(); i++) {
            if(mybookings.get(i).getId() ==id) {
                myBooking = mybookings.get(i);
            }
        }
        
        return myBooking;
        
    }

    public void removeBooking(Booking mpb) {
        mybookings = getMybookings();

        if (mybookings.contains(mpb)) {
            Database.getBookingController().destroy(mpb.getId());
            mybookings.remove(mpb);
        }

    }
}
